using System;
using System.Web.Mvc;
using Ninject;
using Sample1.Web.Models;

namespace Sample1.Web.Controllers
{   
    public class ProductsController : Controller
    {
		private readonly IProductRepository _productRepository;

        [Inject]
        public ProductsController(IProductRepository productRepository)
        {
			this._productRepository = productRepository;
        }

        //
        // GET: /Product/

        public ViewResult Index()
        {
            return View(this._productRepository.GetAllProducts());
        }

        //
        // GET: /Product/Details/5

        public ViewResult Details(int id)
        {
            return View(this._productRepository.GetById(id));
        }

        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Product/Create

        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (_productRepository.Contains(product.Name))
            {
                ModelState.AddModelError("Name", "Already exists another product with that name");
            }

            if (ModelState.IsValid) {
                this._productRepository.InsertOrUpdate(product);
                this._productRepository.Save();
                
                return RedirectToAction("Index");
            }

			return View(product);
        }
        
        //
        // GET: /Product/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View(this._productRepository.GetById(id));
        }

        //
        // POST: /Product/Edit/5

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (product.ProductId == 0)
            {
                throw new ArgumentException("ProductId should be informed");
            }

            if (_productRepository.Contains(product.Name, product.ProductId))
            {
                ModelState.AddModelError("Name", "Already exists another product with that name");
            }

            if (ModelState.IsValid) {
                this._productRepository.InsertOrUpdate(product);
                this._productRepository.Save();
                
                return RedirectToAction("Index");
            }

            return View(product);
        }

        //
        // GET: /Product/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View(this._productRepository.GetById(id));
        }

        //
        // POST: /Product/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            this._productRepository.Delete(id);
            this._productRepository.Save();

            return RedirectToAction("Index");
        }
    }
}

